package rsa.min;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import rsa.lib.Key;
import rsa.lib.PrimeLib;

public class EncryptFile {
	private Key key;
	
	public EncryptFile(Key k){
		this.key = k;
	}
	
	public void Encrypt(String infile, String outfile) throws IOException{
		FileInputStream in = new FileInputStream(infile);
		FileOutputStream out = new FileOutputStream(outfile);
		//DataInputStream in = new DataInputStream(in1);
		
		int nbit = PrimeLib.bitLength(key.getModule());
		int nbyte = nbit/8;
		int ceilbyte = (int) Math.ceil((new Double(nbit))/8.0);
		byte[] data = new byte[nbyte];
		int nbyteread = 0;
		while((nbyteread = in.read(data)) != -1){
			if(nbyteread < nbyte){
				byte[] temp = new byte[nbyteread];
				System.arraycopy(data, 0, temp, 0, nbyteread);
				data = temp;
			}
			int[] tempint = new int[data.length];
			for(int i = 0; i < data.length; i++)
				tempint[i] = (data[i] >= 0?data[i]:0xff & data[i]);
			String s = new String();
			for(int i = 0; i < tempint.length; i++){
				if (tempint[i] < 16)
					s = s + "0";
				s = s + Integer.toString(tempint[i], 16);
			}
			
			BigInteger indata = new BigInteger(s, 16);
			System.out.println("input.txt: " + indata);
			BigInteger outdata = PrimeLib.pow(indata, key.getExponent(), key.getModule());
			System.out.println("output: " + outdata);
			byte[] arr = outdata.toByteArray();
			if(arr[0] == 0){
				byte[] tmp = new byte[arr.length - 1];
				System.arraycopy(arr, 1, tmp, 0, tmp.length);
				arr = tmp;
			}
			if(arr.length < ceilbyte){
				for(int i = 0; i < (ceilbyte - arr.length); i++)
					out.write(0);
			}
			for(int i = 0; i < arr.length; i++)
				out.write(arr[i]);
		}
		in.close();
		out.close();
	}
}
